<?php

namespace addons\workteam\library;


use app\admin\model\Admin;
use app\admin\model\AuthGroup;
use fast\Random;
use fast\Tree;
use think\Config;
use think\Db;

/**
 * 权限管理以及API接口类
 * Class Auth
 * @package addons\workteam\library
 */
class Auth extends \app\admin\library\Auth
{

    protected $_admin = null;
    protected $_token = '';


    /**
     * 根据Token初始化
     *
     * @param string $token Token
     * @return boolean
     */
    public function init($token)
    {

        if ($this->logined) {
            return TRUE;
        }

        if ($this->_error)
            return FALSE;
        $admin = Admin::get(['token' => $token]);

        if (!$admin) {

            $this->setError('You are not logged in');
            return FALSE;
        }

        if ($admin['status'] == "hidden") {
            $this->setError('Account is locked');
            return FALSE;
        }


        if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
            $this->setError('Please try again after 1 day');
            return false;
        }
        $this->_admin = $admin;
        return true;

    }

    /**
     * 获取admin模型
     * @return Admin
     */
    public function getAdmin()
    {
        return $this->_admin;
    }

    /**
     * 兼容调用user模型的属性
     *
     * @param string $name
     * @return mixed
     */
    public function __get($name)
    {
        return $this->_admin ? $this->_admin->$name : null;
    }

    /**
     * 直接登录账号
     * @param int $admin_id
     * @return Admin
     */
    public function direct($admin_id)
    {

        if ($this->logined) {
            return TRUE;
        }

        if ($this->_error)
            return FALSE;
        $admin = Admin::get(['id' => $admin_id]);

        if (!$admin) {
            $this->setError('You are not logged in');
            return FALSE;
        }

        if ($admin['status'] == "hidden") {
            $this->setError('Account is locked');
            return FALSE;
        }


        if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
            $this->setError('Please try again after 1 day');
            return false;
        }
        $admin->loginfailure = 0;
        $admin->logintime = time();
        $admin->loginip = request()->ip();
        $admin->token = Random::uuid();
        $admin->save();
        $this->_admin = $admin;
        return $admin;

    }

    /**
     * 管理员登录
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param int $keeptime 有效时长
     * @return  boolean
     */
    public function login($username, $password, $keeptime = 0)
    {
        $admin = Admin::get(['username' => $username]);
        if (!$admin) {
            $this->setError('Username is incorrect');
            return false;
        }
        if ($admin['status'] == 'hidden') {
            $this->setError('Admin is forbidden');
            return false;
        }
        if (Config::get('fastadmin.login_failure_retry') && $admin->loginfailure >= 10 && time() - $admin->updatetime < 86400) {
            $this->setError('Please try again after 1 day');
            return false;
        }
        if ($admin->password != md5(md5($password) . $admin->salt)) {
            $admin->loginfailure++;
            $admin->save();
            $this->setError('Password is incorrect');
            return false;
        }
        $admin->loginfailure = 0;
        $admin->logintime = time();
        $admin->loginip = request()->ip();
        $admin->token = Random::uuid();
        $admin->save();
        $this->_admin = $admin;
        $this->keeplogin($keeptime);
        return true;
    }

    /**
     * 检测是否登录
     *
     * @return boolean
     */
    public function isLogin()
    {
        if ($this->logined) {

            return true;
        }

        if ($this->_admin) {
            return true;
        }

        //判断管理员IP是否变动
        if (Config::get('fastadmin.loginip_check')) {
            if (!isset($this->_admin['loginip']) || $this->_admin['loginip'] != request()->ip()) {
                $this->logout();
                return false;
            }
        }
        $this->logined = false;
        return false;
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $admin = Admin::get(intval($this->id));
        if ($admin) {
            $admin->token = '';
            $admin->save();
        }
        $this->logined = false; //重置登录状态
        return true;
    }

    /**
     * 获取直接父IDS
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getParentAdminIds($uid)
    {
        $parentAdminIds = [];
        $groupIds = $this->getParentGroupIds($uid);
        $authGroupList = \app\admin\model\AuthGroupAccess::
        field('uid,group_id')
            ->where('group_id', 'in', $groupIds)
            ->select();
        foreach ($authGroupList as $k => $v) {
            $parentAdminIds[] = $v['uid'];
        }
        return $parentAdminIds;
    }

    /**
     * 取出当前管理员所有的父级组IDS
     * @return array
     */
    public function getParentGroupIds($uid)
    {
        //取出当前管理员所有的分组
        $groups = $this->getGroups($uid);

        $groupIds = [];
        foreach ($groups as $k => $v) {
            $groupIds[] = $v['id'];
        }

        $originGroupIds = $groupIds;
        foreach ($groups as $k => $v) {
            if (in_array($v['pid'], $originGroupIds)) {
                $groupIds = array_diff($groupIds, [$v['id']]);
                unset($groups[$k]);
            }
        }
        // 取出所有分组
        $groupList = \app\admin\model\AuthGroup::where(['status' => 'normal'])->select();
        $parentGroupIds = [];
        foreach ($groups as $k => $v) {
            // 取出包含自己的所有子节点
            $temp = Tree::instance()->init($groupList)->getParent($v['id'], true);
            if ($temp) {
                foreach ($temp as $row) {
                    if (!in_array($row['id'], $parentGroupIds)) {
                        $parentGroupIds[] = $row['id'];
                    }

                }
            }
        }
        return $parentGroupIds;
    }

    /**
     * 检查是否有项目[读取]的权限
     * @param $project 一个项目对象或项目ID
     * @param $auth 当前登录后台的权限对象
     * @return bool|int|string
     * @throws \think\Exception
     */
    public function projectAuth($project, $auth, $type = 'all')
    {

        if ($auth->isSuperAdmin()) {
            return true;
        }
        if (!$project) return false;
        if (is_numeric($project)) {
            $projectModel = new \app\admin\model\workteam\Project();
            //如果传的是项目ID 获取对象
            $project = $projectModel->where('id', $project)->fetchSql(false)->find();
        }
        if (!$project) return false;

        $childrenAdminIds = $this->childrenAdminIds($auth, true);
        //是否属于自己和下属的任务
        if (in_array($project['project_admin_id'], $childrenAdminIds)) {
            return true;
        }

        //是否是参与人员
        if (in_array($auth->id, explode(',', $project['admin_ids']))) {
            return true;
        }
		 //业务人员
        if ($auth->id==$project['sales_admin_id']) {
            return true;
        }
        return false;

    }

    /**
     * 检查是否有项目[修删]的权限
     * @param $project 一个项目对象或项目ID
     * @param $auth 当前登录后台的权限对象
     * @return bool|int|string
     * @throws \think\Exception
     */
    public function edProjectAuth($project, $auth)
    {

        if ($auth->isSuperAdmin()) {
            return true;
        }
        if (!$project) return false;
        if (is_numeric($project)) {
            $projectModel = new \app\admin\model\workteam\Project();
            //如果传的是项目ID 获取对象
            $project = $projectModel->where('id', $project)->fetchSql(false)->find();
        }
        if (!$project) return false;
        $childrenAdminIds = $this->childrenAdminIds($auth, true);
        //是否属于自己和下属的任务
        if (in_array($project['project_admin_id'], $childrenAdminIds)) {
            return true;
        }
    }


    /**
     * 检查是否有任务[读取]的权限
     * @param $task 一个任务对象或任务ID
     * @param $auth 当前登录后台的权限对象
     * @return bool|int|string
     * @throws \think\Exception
     */
    public function taskAuth($task, $auth)
    {

        //是否是超级管理人员
        if ($auth->isSuperAdmin()) {
            return true;
        }
        if (!$task) return false;
        if (is_numeric($task)) {
            $taskModel = new \app\admin\model\workteam\Task();
            //如果传的是任务ID 获取对象
            $task = $taskModel->where('id', $task)->fetchSql(false)->find();
        }
        if (!$task) return false;


        //是否是项目管理人员
        if ($task->project->project_admin_id == $auth->id)
            return true;
		
		//业务人员
        if ($auth->id==$task->project['sales_admin_id']) {
            return true;
        }
		
        $childrenAdminIds = $this->childrenAdminIds($auth, true);
        //是否属于自己和下属的任务
        if (in_array($task['admin_id'], $childrenAdminIds)) {
            return true;
        }
        //是否是任务参与人员
        if (in_array($auth->id, explode(',', $task['admin_ids']))) {
            return true;
        }
        return false;

    }


    /**
     * 检查是否有任务[修删]的权限
     * @param $task 一个任务对象或任务ID
     * @param $auth 当前登录后台的权限对象
     * @param $project_admin_id 项目管理人员id
     * @return bool|int|string
     * @throws \think\Exception
     */
    public function edTaskAuth($task, $auth)
    {

        //是否是超级管理人员
        if ($auth->isSuperAdmin()) {
            return true;
        }
        if (!$task) return false;
        if (is_numeric($task)) {
            $taskModel = new \app\admin\model\workteam\Task();
            //如果传的是任务ID 获取对象
            $task = $taskModel->where('id', $task)->fetchSql(false)->find();
        }
        if (!$task) return false;

        //是否是项目管理人员
        if ($task->project->project_admin_id == $auth->id)
            return true;

        $childrenAdminIds = $this->childrenAdminIds($auth, true);
        //是否属于自己和下属的任务
        if (in_array($task['admin_id'], $childrenAdminIds)) {
            return true;
        }

        return false;

    }

    /**
     * 取出下属员工ids
     * @param boolean $withself 是否包含自身
     * @return array
     */
    public function childrenAdminIds($auth, $withself = false)
    {
        $department = get_addon_info('department');

        if ($department && $department['state'] == 1) {

            $childrenAdminIds = \app\admin\model\department\Admin::getChildrenAdminIds($auth->id, $withself);
        } else {
            $childrenAdminIds = $auth->getChildrenAdminIds($withself);
        }

        return $childrenAdminIds;
    }

    /**
     * 获取所有部门
     */
    public function getAllDepartmentsTreeArray($admin_id)
    {
        $department = get_addon_info('department');
        $groupdata = [];
        if ($department && $department['state'] == 1) {
            $groupdata = \app\admin\model\department\Admin::getAllDepartmentsTreeArray($admin_id, true);

        } else {
            $groupList = collection(\app\admin\model\AuthGroup::select())->toArray();
            Tree::instance()->init($groupList);
            $result_arr = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result_arr as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        }
        return $groupdata;
    }

    /**
     * 获取部门ID
     */
    public function getDepartmentIds($auth, $is_principal = false)
    {
        $department = get_addon_info('department');
        if ($department && $department['state'] == 1) {
            $departmentIds = \app\admin\model\department\Admin::getDepartmentIds($auth->id, $is_principal);

        } else {
            $departmentIds = $auth->getGroupIds();
        }
        return $departmentIds;
    }

    /**
     * 获取指定部门的员工的IDS
     * @return array
     */
    public function getDepartmentAdminIds($auth, $department_id, $withself = true)
    {
        $department = get_addon_info('department');

        if ($department && $department['state'] == 1) {
            $department_ids = \app\admin\model\department\Department::getChildrenIds($department_id);
            $childrenAdminIds = \app\admin\model\department\Admin::getDepartmentAdminIds($department_ids);
        } else {
            $childrenGroupIds = $auth->getChildrenGroupIds(true);
            $groupList = collection(AuthGroup::where('id', 'in', $childrenGroupIds)->select())->toArray();
            Tree::instance()->init($groupList);
            $groupIds = Tree::instance()->getChildrenIds($department_id, true);

            $authGroupList = \app\admin\model\AuthGroupAccess::
            field('uid,group_id')
                ->where('group_id', 'in', $groupIds)
                ->select();
            $childrenAdminIds = array();
            foreach ($authGroupList as $k => $v) {
                if ($childrenAdminIds && in_array($v['uid'], $childrenAdminIds)) continue;
                $childrenAdminIds[] = $v['uid'];
            }
        }

        return $childrenAdminIds;
    }

}
